import os
import re
import requests
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from requests.adapters import HTTPAdapter
from urllib3 import Retry

_invalid_re = re.compile(r'[<>:"/\\|?*\x00-\x1F]')


def sanitize_filename(name: str) -> str:
    s = _invalid_re.sub("_", str(name or "")).strip().strip(". ")
    return s or "untitled"


def unique_path(out_dir: str, filename: str) -> str:
    base, ext = os.path.splitext(filename)
    base = sanitize_filename(base)
    candidate = os.path.join(out_dir, base + ext)
    i = 1
    while os.path.exists(candidate):
        candidate = os.path.join(out_dir, f"{base}_{i}{ext}")
        i += 1
    return candidate


def build_session() -> requests.Session:
    s = requests.Session()
    retries = Retry(
        total=3,
        backoff_factor=0.6,
        status_forcelist=(429, 500, 502, 503, 504),
        allowed_methods=frozenset(["GET", "HEAD"]),
        raise_on_status=False,
    )
    adapter = HTTPAdapter(max_retries=retries, pool_connections=16, pool_maxsize=16)
    s.mount("http://", adapter)
    s.mount("https://", adapter)
    s.headers.update({
        "User-Agent": (
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/127.0.0.0 Safari/537.36"
        ),
        "Accept": "*/*",
        "Referer": "https://fgo.wiki/",
        "Origin": "https://fgo.wiki",
    })
    return s


def ensure_placeholder(pix_size=200):
    pm = QPixmap(pix_size, pix_size)
    pm.fill(Qt.lightGray)
    return pm
